package org.dandelion.papercheck.controller;

import org.dandelion.papercheck.annotation.UserLoginToken;
import org.dandelion.papercheck.dto.BaseResult;
import org.dandelion.papercheck.dto.HistoryDTO;
import org.dandelion.papercheck.dto.HistoryDetailDTO;
import org.dandelion.papercheck.dto.HistoryResults;
import org.dandelion.papercheck.entity.History;
import org.dandelion.papercheck.service.HistoryService;
import org.dandelion.papercheck.util.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


@SuppressWarnings("rawtypes")
@CrossOrigin
@RestController
public class HistoryController {

    private final HistoryService historyService;

    @Autowired
    public HistoryController(HistoryService historyService) {
        this.historyService = historyService;
    }

    @UserLoginToken
    @RequestMapping(path = "/queryHistory")
    public BaseResult queryHistory(HttpServletRequest httpServletRequest,
                                   @RequestParam(value = "size", required = false, defaultValue = "5") Integer size,
                                   @RequestParam(value = "page", required = false, defaultValue = "0") Integer page) {
        List<History> histories = historyService.getHistory(JWTUtils.getIdFromRequest(httpServletRequest), size, page);
        HistoryResults historyResults = new HistoryResults();

        for (History history : histories) {
            historyResults.add(new HistoryDTO(history.getId(), history.getArticle().getOriginalName(),
                    history.getCreateDateTime()));
        }

        return BaseResult.success(historyResults);
    }

    @RequestMapping("historyDetail")
    public BaseResult historyDetail(@RequestParam String historyId) {
        try {
            Long id = Long.parseLong(historyId);
            List<HistoryDetailDTO> detailDTOs = historyService.getDetail(id);
            return BaseResult.success(detailDTOs);
        } catch (Exception e) {
            return BaseResult.error(500, e.getMessage());
        }
    }

}
